package com.matt.controller.pad;

import com.matt.commons.dto.sso.AreaDTO;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.model.StatusResponse;
import com.matt.domain.AppSkin;
import com.matt.domain.course.Course;
import com.matt.domain.course.PrepareRemind;
import com.matt.domain.rel.RelClassesTeacher;
import com.matt.foundation.DO.ClassListDO;
import com.matt.foundation.DO.course.PrepareStaffDO;
import com.matt.foundation.constant.PermissionConstant;
import com.matt.foundation.constant.RequestConstant;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.utils.DateUtil;
import com.matt.service.*;
import com.matt.service.remoteCall.DTO.RoleDTO;
import com.matt.service.remoteCall.SsoCallService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

import static com.matt.foundation.constant.RequestConstant.TICKET;

/**
 * *******************************
 * Created by Ron.
 * form com.matt
 * on 2017/7/11
 * *******************************
 */
@RestController
@RequestMapping("/pad/teacher")
public class PadTeacherController {

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private ClassesService classesService;

    @Autowired
    private MemVerificationCache cache;

    @Autowired
    private PrepareCourseService prepareCourseService;

    @Autowired
    private RelClassesTeacherService relClassesTeacherService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private PrepareRemindService prepareRemindService;

    @Autowired
    private AppSkinService appSkinService;

    @ApiOperation(value = "当前教师对象",httpMethod = "GET")
    @RequestMapping("/base_info")
    public StatusResponse baseInfo(@RequestHeader(RequestConstant.TICKET) String ticket) {
        StaffDTO staff = ssoCallService.getStaffDTO(ticket);
        return StatusResponse.success(staff);
    }

    //TODO 为了兼容原有字段
    @ApiOperation(value = "教室详情，以及权限等", httpMethod = "GET")
    @RequestMapping("/info")
    public StatusResponse detail(@RequestHeader(RequestConstant.TICKET) String ticket,@RequestHeader(required = false) String platformId) {
        Map response = ssoCallService.getPermissionInfoV2(ticket, 1, platformId);
        if (response == null){
            throw new BusinessException("SSO获取权限失败");
        }

        Map staff = (Map) response.get("staff");
        if (staff == null){
            throw new BusinessException("SSO获取权限失败!");
        }

        String staffId = (String) staff.get("id");
        String areaId = (String) staff.get("areaId");
        if (StringUtils.isEmpty(staffId)){
            throw new BusinessException("SSO获取权限失败!!");
        }

        AppSkin skin =  appSkinService.getPersonalSkin(areaId);
        response.put("appSkin", skin);

//        List<RoleDTO> roleList = ssoCallService.getStaffRoleList(ticket);
        RoleDTO defaultRole = ssoCallService.getStaffRole(ticket);
//        AreaDTO areaDTO = ssoCallService.getAreaDTO(ticket);
//
//
//        List<PlatformMenuDto> menus = ssoCallService.getRoleMenus(ticket, defaultRole.getId(), 1);
//
        String roleCode = PermissionConstant.Role.TEACHER.codeOf();
        if (ssoCallService.checkStaffPermission(ticket, new String[]{PermissionConstant.TEACH_CLASSES_FULL})){
            roleCode = PermissionConstant.Role.GARDEN_LEADER.codeOf();
        }else if (ssoCallService.checkStaffPermission(ticket, new String[]{PermissionConstant.TEACH_CLASSES_DOCTOR})){
            roleCode = PermissionConstant.Role.DOCTOR.codeOf();
        }

        List<ClassListDO> classesList = classesService.getClassesByStaffId(roleCode, staffId, areaId);
        response.put("classList", classesList);

        response.put("defaultRole", defaultRole);
//
//        response.put("area", areaDTO);
//
//        response.put("menus", menus);
//
        return StatusResponse.success(response);
    }

    @ApiOperation(value = "媒体对象统计", httpMethod = "GET")
    @RequestMapping("/media_statistics")
    public StatusResponse mediaStatistics(String teacherId) {
        Map response = teacherService.getMediaStatisticsInfo(teacherId);
        return StatusResponse.success(response);
    }

    @ApiOperation(value = "修改密码", httpMethod = "POST")
    @RequestMapping("/modify_password")
    public StatusResponse modifyPassword(@RequestHeader(RequestConstant.TICKET) String ticket, String oldPassword, String newPassword) {
        Map response = ssoCallService.resetPassword(ticket, oldPassword, newPassword);
        return StatusResponse.success(response);
    }

    @ApiOperation(value = "根据ID查询用户对象", httpMethod = "POST")
    @RequestMapping("/info_by_staffId")
    public StatusResponse getInfoByStaffId(@RequestHeader(RequestConstant.TICKET) String ticket, String staffId) {
        StaffDTO staffDTO = ssoCallService.getStaffDTO(ticket, staffId);
        return StatusResponse.success(staffDTO);
    }

    /**
     * 查询园区老师进入备课情况
     * @param ticket
     * @return
     */
    @ApiOperation(value = "园区贝壳老师列表", httpMethod = "GET")
    @RequestMapping("/get_prepare_teacher_list")
    public StatusResponse getPrepareTeacherList(@RequestHeader(TICKET) String ticket) {
        String areaId = cache.getStaff(ticket).getAreaId();
        String  today = DateUtil.getToday();
        Date todayBegin = DateUtil.getCurrentDayBeginAndEnd(DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM-dd")).get("beg");
        Date todayEnd = DateUtil.getCurrentDayBeginAndEnd(DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM-dd")).get("end");

        List<Map> response = new ArrayList<>();
        List<PrepareStaffDO> coursePlancClassList =  prepareCourseService.getCoursePlanClassList(areaId, today);//查询当日全区排课情况
        for(PrepareStaffDO c : coursePlancClassList){
            int prepareStatus = c.getPrepareStatus();//备课状态： 0:未备课,1:已备课 2:待审核, 3:未通过, 4:已通过
            String courseId = c.getCourseId();
            String classesId = c.getClassesId();
            String coursePlanClassesId =c.getCoursePlanClassesId();
            List<RelClassesTeacher> relClassesTeacherList = relClassesTeacherService.findByClassesId(classesId);

            String[] staffIds = relClassesTeacherList.stream().map(o->o.getStaffId()).toArray(String[]::new);
            List<StaffDTO> staffs = ssoCallService.getStaffDTOList(ticket, staffIds);

            List<Map> res = staffs.stream().map( sd -> {
                String teacherName = sd.getRealName();
                String teacherId = sd.getId();
                Boolean isRemind = false;//默认没有提醒过
                List<PrepareRemind> staffPrepareRemindList = prepareRemindService.findByStaffIdAndPlanIdAndRemindDateBetween(teacherId, coursePlanClassesId, todayBegin, todayEnd);
                if(staffPrepareRemindList.size()>0){
                    isRemind = true ;
                }

                Map m = new HashMap<>();
                m.put("teacherName",teacherName);
                m.put("teacherId",teacherId);
                m.put("prepareStatus",prepareStatus);
                m.put("planId",coursePlanClassesId);
                m.put("courseId",c.getCourseId());
                m.put("courseName",c.getCourseName());
                m.put("classesId",c.getClassesId());
                m.put("classesName", c.getClassesName());
                m.put("isRemind",isRemind);

                return m;
            }).collect(Collectors.toList());

            response.addAll(res);
        }

        return StatusResponse.success(response);
    }

    /**
     * 园长督促老师备课
     * @param ticket
     * @return
     */
    @ApiOperation(value = "备课提醒", httpMethod = "POST")
    @RequestMapping("/prepareRemind")
    public StatusResponse prepareRemind(@RequestHeader(TICKET) String ticket,String planId,String courseId,String staffId) {
        String title = "备课提醒";

        String areaId = cache.getStaff(ticket).getAreaId();
        Course course  = courseService.getById(courseId);
        String courseName = course.getName();

        StaffDTO sd = ssoCallService.getStaffDTO(ticket, staffId);

        String staffName = sd.getRealName();
        String content = "今日"+courseName+"你还未备课。";

        PrepareRemind remind = new PrepareRemind();
        remind.setAreaId(areaId);
        remind.setCourseId(courseId);
        remind.setCourseName(courseName);
        remind.setStaffId(staffId);
        remind.setStaffName(staffName);
        remind.setRemindDate(new Date());
        remind.setPlanId(planId);
        prepareRemindService.save(remind);

//        redPointService.addPrepareRemindRedNum(areaId, staffId, staffName, RedPointConstant.RED_POINT_PREPARE_COURSE, 1, title, content);
        return StatusResponse.success(remind);
    }

//   //查询备课提醒信息列表
//    @RequestMapping("/getPreparRemindList")
//    public StatusResponse getPreparRemindList(@RequestHeader(TICKET) String ticket, PagerQuery query){
//        String staffId =cache.getStaffId(ticket) ;
//        Page<RedPointRecord> recordPage = redPointRecordService.getPreparRemindList(staffId, RedPointConstant.RED_POINT_PREPARE_COURSE, query.getPageNum(), query.getPageSize());
//        return StatusResponse.success(recordPage);
//    }


    //查询某人 备课提醒红点数量
//    @RequestMapping("/getPreparRemindNum")
//    public StatusResponse getPreparRemindNum(@RequestHeader(TICKET) String ticket,String pointCode){
//        String staffId =cache.getStaffId(ticket) ;
//        int num = redPointService.getPrePareRemindRedNum(staffId, pointCode);
//        Map m = new HashMap<>();
//        m.put("staffId",staffId);
//        m.put("redNum",num);
//        return StatusResponse.success(m);
//    }


    //设置默认岗位
    @ApiOperation(value = "设置默认岗位", httpMethod = "POST")
    @RequestMapping("/set_default_role")
    public StatusResponse setDefaultStaffPosition(@RequestHeader(TICKET) String ticket,String roleId){
        String staffId = cache.getStaffId(ticket);
        RoleDTO result = ssoCallService.setDefaultRole(ticket,  roleId);
        return StatusResponse.success(result);
    }



    @ApiOperation(value = "修改园区",httpMethod = "POST")
    @RequestMapping(value = "/change_area", method = RequestMethod.POST)
    public StatusResponse changeArea(@RequestHeader(TICKET) String ticket, String areaId) {
        AreaDTO result = ssoCallService.setDefaultArea(ticket, areaId);
        return StatusResponse.success(result);
    }

}
